package com.ruoyi.api.controller;

import com.ruoyi.api.service.FenceService;
import com.ruoyi.api.service.HazardousAreasService;
import com.ruoyi.api.service.impl.LocationServiceImpl;
import com.ruoyi.api.utils.SysMath;
import com.ruoyi.api.vo.FenceDemo;
import com.ruoyi.api.vo.FenceInfo;
import com.ruoyi.api.vo.Hazardous;
import com.ruoyi.api.vo.HazardousDemo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static org.apache.commons.lang3.ObjectUtils.*;

/**
 * 危险区域提示
 */
@RestController
@RequestMapping("/api/sys/hazardousareas")
public class HazardousAreasController {

    @Autowired
    private HazardousAreasService hazardousAreasService;

    @Autowired
    private LocationServiceImpl locationService;

    @Autowired
    private FenceService fenceService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询用户当前位置是否在危险区域内，在的话返回区域id，不在的话返回提示信息
     * @param hazardous
     * @return
     */
    @PostMapping("/unhazardous")
    public AjaxResult hazardous(@RequestBody Hazardous hazardous){
        //获取用户的最新位置
        String location = locationService.selectUserLocation(hazardous.getUserId());
        hazardous.setLocation(location);
        Object a = hazardousAreasService.selectHazardous(hazardous);
        String b = String.valueOf(a);
        if(b.equals("true")){
            return AjaxResult.success(hazardous);
        }
        return AjaxResult.success("未进入危险区域");
    }

    /**
     * 添加用户进出危险区域信息
     * @param
     * @return
     */
    @GetMapping("/addhazardous")
    public AjaxResult addhazardous(@RequestParam String userId) {
        FenceDemo fenceDemo = new FenceDemo();
        List<FenceInfo> list3 = new ArrayList<>();
        //获取所有的电子围栏信息
        List<FenceInfo> list = fenceService.selectAll();
        Map<Integer,Object> map = new HashMap<>();
        for (int i = 0; i < list.size(); i++) {
            //转换判断进入对象类型
            Hazardous hazardous = getHazardous(list.get(i));
            hazardous.setUserId(userId);
            //获取用户的最新位置
            String location = locationService.selectUserLocation(hazardous.getUserId());
            hazardous.setLocation(location);
            Object a = new Object();
            //电子围栏为圆,判断其状态
            if(hazardous.getType() == 3){
                String[] w = location.split(",");
                Double m = hazardousAreasService.stDistance(Double.valueOf(w[0]), Double.valueOf(w[1]), Double.valueOf(hazardous.getLon()), Double.valueOf(hazardous.getLat()));
//                        SysMath.GetDistance(Double.valueOf(w[0]), Double.valueOf(w[1]), Double.valueOf(hazardous.getLon()), Double.valueOf(hazardous.getLat()));
                if (m <= Double.valueOf(hazardous.getRadius())) {
                    a = true;
                } else {
                    a = false;
                }
            }else{
                //判断是否进入电子围栏
                a = hazardousAreasService.selectHazardous(hazardous);
            }
            if((Boolean)a == true){
                list3.add(list.get(i));
            }
            map.put(list.get(i).getFenceId(),a);
        }
        fenceDemo.setCurrent(list3);
        List<FenceInfo> list1 = new ArrayList<>();
        List<FenceInfo> list2 = new ArrayList<>();
        //获取上个点的状态,如果上各点的状态长度为0,将现在点的状态进行赋值
        Map<Integer,Object> q = new HashMap<>();
        Map<Integer,Object> c = redisCache.getCacheObject("Hazardous:" + userId);
        if(isEmpty(c)) {
            for (Map.Entry<Integer, Object> entry : map.entrySet()) {
                q.put(entry.getKey(), entry.getValue());
            }
            c = q;
        }
        Set set = c.keySet();
        for (FenceInfo fenceInfo : list) {
            for (Object o : set) {
                //判断如果两个值相等,说明为同一个电子围栏
                if (fenceInfo.getFenceId() == o) {
                    Object b = c.get(o);
                    Object a = map.get(o);
                    //未进入电子围栏
                    if ((Boolean) a == false && (Boolean) b == false) {
                        continue;
                    }
                    //前一个状态为false后一个状态为true,说明在此时间段进入电子围栏
                    if ((Boolean) a == true && (Boolean) b == false) {
                        //根据围栏对象转换用户保存对象
                        HazardousDemo hazardousDemo = getHazardousDemo(fenceInfo);
                        hazardousDemo.setUserId(Long.valueOf(userId));
                        hazardousAreasService.add(hazardousDemo);
                        //围栏状态为禁入或者为禁出入
//                        if (fenceInfo.getFenceType().equals(0) || fenceInfo.getFenceType().equals(2)) {
//                            list1.add(fenceInfo);
//                        }
                        list1.add(fenceInfo);
                    }
                    //一直处于围栏区域,不做操作
                    if ((Boolean) a == true && (Boolean) b == true) {
                        continue;
                    }
                    if ((Boolean) a == false && (Boolean) b == true) {
                        //未在电子围栏
                        list2.add(fenceInfo);
                        //查询最后添加的数据并修改结束时间为当前时间
                        HazardousDemo hazardousDemo = getHazardousDemo(fenceInfo);
                        Date date = new Date();
                        DateFormat dateFormats = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
                        String times = dateFormats.format(date);
                        hazardousAreasService.updateById(hazardousDemo.getId(), times);
                    }
                }
            }
        }
        fenceDemo.setEnterFence(list1);
        fenceDemo.setLeaveFence(list2);
        redisCache.setCacheObject("Hazardous:" + userId, map,10,TimeUnit.MINUTES);
        return AjaxResult.success(fenceDemo);
    }

    /**
     * 通过用户Id查询用户进出危险区域信息
     * @param userId
     * @return
     */
    @PostMapping("/select")
    public AjaxResult selectHazardous(@RequestParam String userId){
        return AjaxResult.success();
    }

    /**
     * 删除信息
     * @param id
     * @return
     */
    @DeleteMapping("/delect")
    public AjaxResult delectHazardous(@RequestBody String id){
        return AjaxResult.success();
    }


    /**
     * 类型转换
     * @param fenceInfo
     * @return
     */
    private Hazardous getHazardous(FenceInfo fenceInfo){
        Hazardous hazardous = new Hazardous();
        hazardous.setRegion(fenceInfo.getFenceGis());
        hazardous.setType(Integer.valueOf(fenceInfo.getFenceShape()));
        hazardous.setLat(fenceInfo.getLat());
        hazardous.setLon(fenceInfo.getLon());
        hazardous.setRadius(fenceInfo.getRadius());
        return hazardous;
    }

    private HazardousDemo getHazardousDemo(FenceInfo fenceInfo) {
        HazardousDemo hazardousDemo = new HazardousDemo();
        Date date = new Date();
        DateFormat dateFormats = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        String times = dateFormats.format(date);
        hazardousDemo.setBeginTime(times);
        hazardousDemo.setType(fenceInfo.getFenceShape());
        hazardousDemo.setSpare(fenceInfo.getSpare1());
        hazardousDemo.setFenceType(fenceInfo.getFenceType());
        hazardousDemo.setFenceGis(fenceInfo.getFenceGis());
        hazardousDemo.setFenceName(fenceInfo.getFenceName());
        hazardousDemo.setFenceId(fenceInfo.getFenceId());
        return hazardousDemo;
    }
}

//            //离开围栏区域!
//            if ((Boolean) a == false && (Boolean)b == true) {
//                h = 0;
//                if(i == 0){
//                    HazardousDemo hazardousDemo = getHazardousDemo(list.get(i));
//                    hazardousDemo.setUserId(Long.valueOf(userId));
//                    //查询最后添加的数据并修改结束时间为当前时间
//                    String id = hazardousAreasService.selectId(userId);
//                    hazardousAreasService.updateById(id);
//                    //围栏状态为禁出或者为禁出入
//                    if (equals(list.get(i).getFenceType().equals(1)) || equals(list.get(i).getFenceType().equals(2))){
//                        return AjaxResult.success(hazardousDemo);
//                    }
//                }
//                HazardousDemo hazardousDemo = getHazardousDemo(list.get(i-1));
//                hazardousDemo.setUserId(Long.valueOf(userId));
//                //查询最后添加的数据并修改结束时间为当前时间
//                String id = hazardousAreasService.selectId(userId);
//                hazardousAreasService.updateById(id);
//                //围栏状态为禁出或者为禁出入
//                if (list.get(i).getFenceType().equals("1") && list.get(i).getFenceType().equals("2")) {
//                    return AjaxResult.success(hazardousDemo);
//                }
//            }
//        }



//        //转换判断进入对象类型
//        Hazardous hazardous = getHazardous(list.get(i));
//        hazardous.setUserId(userId);
//        //获取用户的最新位置
//        String location = locationService.selectUserLocation(hazardous.getUserId());
//        hazardous.setLocation(location);
//        //判断是否进入电子围栏
//        Object a = hazardousAreasService.selectHazardous(hazardous);
//判断如果为false不在电子围栏内,不进行下面操作,跳过本次循环
